# Build script for the robert bootloader
#
# This bootloader is different than the other bootloaders that are in the platform/boot tree
# because it's still in development, so it's built as part of the normal firmware build, including
# using the environments and waftools that are part of the firmware build. At a later point, we'll
# want to split this out again to be more like the other bootloaders.

import sys
import os
from waflib import Logs

sys.path.append(os.path.abspath('waftools'))
import gitinfo
import objcopy

waf_dir = sys.path[0]
sys.path.append(os.path.abspath('waftools'))
sys.path.append(os.path.join(waf_dir, '../../../tools'))

def options(opt):
    opt.load('gcc')
    opt.add_option('--board', action='store',
                   choices=['robert_bb', 'robert_bb2', 'cutts_bb', 'robert_evt'],
                   help='Which board to build for (robert_bb, robert_bb2, cutts_bb, robert_evt)')
    opt.add_option('--nowatchdog', action='store_true',
                   help='Disable automatic reboots when watchdog fires')
    opt.add_option('--display_test', action='store_true', help='Enables the diplsay test loop')


def configure(conf):
    conf.env.BOARD = conf.options.board if conf.options.board != 'cutts_bb' else 'robert_bb'

    # Find our binary tools
    conf.find_program('arm-none-eabi-gcc', var='CC', mandatory=True)
    conf.env.AS = conf.env.CC
    conf.find_program('arm-none-eabi-gcc-ar', var='AR', mandatory=True)

    conf.load('gcc')
    conf.load('binary_header')

    for tool in 'ar objcopy'.split():
        conf.find_program('arm-none-eabi-' + tool, var=tool.upper(),
                          mandatory=True)

    # Set up our compiler configuration
    CPU_FLAGS = ['-mcpu=cortex-m7', '-mthumb']
    OPT_FLAGS = ['-Os', '-g']
    C_FLAGS = [
        '-std=c11', '-ffunction-sections',
        '-Wall', '-Wextra', '-Werror', '-Wpointer-arith',
        '-Wno-unused-parameter', '-Wno-missing-field-initializers',
        '-Wno-error=unused-function', '-Wno-error=unused-variable',
        '-Wno-error=unused-parameter', '-Wno-error=unused-but-set-variable',
        '-Wno-packed-bitfield-compat'
        ]
    LINK_FLAGS = ['-Wl,--gc-sections', '-specs=nano.specs']

    conf.env.append_unique('CFLAGS', CPU_FLAGS + OPT_FLAGS + C_FLAGS)
    conf.env.append_unique('LINKFLAGS', LINK_FLAGS + CPU_FLAGS + OPT_FLAGS)

    if conf.options.nowatchdog:
        conf.env.append_unique('DEFINES', 'NO_WATCHDOG')

    if conf.options.display_test:
        conf.env.append_unique('DEFINES', 'DISPLAY_DEMO_LOOP')

    conf.env.append_unique('DEFINES', [
        '_REENT_SMALL=1',
        'USE_STDPERIPH_DRIVER=1',
        'BOARD_{}=1'.format(conf.env.BOARD.upper())
        ])


    # Load up other waftools that we need
    conf.load('objcopy ldscript', tooldir='waftools')

    conf.recurse('vendor')


def size_bootloader(ctx):
    """prints size information of the firmware"""

    elf = ctx.path.get_bld().find_node('robert_boot.elf')
    if elf is None:
        ctx.fatal('No bootloader ELF found for size')

    bin = ctx.path.get_bld().find_node('robert_boot.hex')
    if bin is None:
        ctx.fatal('No bootloader BIN found for size')

    import binutils
    text, data, bss = binutils.size(elf.abspath())
    total = text + data
    output = ('{:>7}    {:>7}    {:>7}    {:>7}    {:>7} filename\n'
              '{:7}    {:7}    {:7}    {:7}    {:7x} robert_boot.elf'.
              format('text', 'data', 'bss', 'dec', 'hex', text, data, bss, total, total))
    Logs.pprint('ORANGE', '\n' + output)

    MAX_SIZE = 32 * 1024

    if total > MAX_SIZE:
        ctx.fatal('Bootloader is too large! Size is 0x%x should be less than 0x%x'
                  % (total, MAX_SIZE))
    else:
        Logs.pprint('ORANGE', 'Bootloader: {}/{} bytes used ({} free)\n'.format(total, MAX_SIZE,
                    MAX_SIZE - total))


def build(bld):
    elf_node = bld.path.get_bld().make_node('robert_boot.elf')

    bld.recurse('vendor')

    linkflags = ['-Wl,-Map,robert_boot.map']

    sources = ['src/*.c',
               'src/drivers/**/*.c',
               'src/system/**/*.c',
               'src/util/**/*.c']

    if bld.env.BOARD in ('robert_bb', 'robert_bb2'):
        sources.append('src/board/board_robert_bb.c')
    elif bld.env.BOARD in ('robert_evt',):
        sources.append('src/board/board_robert_evt.c')
    else:
        bld.fatal("Invalid board set %s" % bld.env.BOARD)

    includes = ['src']

    _generate_fpga_header(bld)

    bld(features='subst',
        source='src/git_version.auto.h.in',
        target='src/git_version.auto.h',
        **gitinfo.get_git_revision(bld))

    bld.program(features="objcopy",
                source=bld.path.ant_glob(sources),
                includes=includes,
                target=elf_node,
                ldscript='src/stm32f_flash_boot.ld',
                linkflags=linkflags,
                objcopy_bfdname='ihex',
                objcopy_target=elf_node.change_ext('.hex'),
                use=['stm32_stdlib'])
    bld(rule=objcopy.objcopy_simple_bin, source='robert_boot.elf', target='robert_boot.bin')

    bld.add_post_fun(size_bootloader)


def _generate_fpga_header(bld):
    bld(features='binary_header',
        source='../Robert_UL1K_bootloader_bitmap.fpga',
        target='src/drivers/display/bootloader_fpga_bitstream.auto.h',
        array_name='s_fpga_bitstream',
        compressed=True)

# vim:filetype=python
